package com.zhangxiaofanfan.hotcode.first;


import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author zhangxiaofanfan
 * @date 2024-06-26 20:33:33
 */
public class HotCode059 {
    public static void main(String[] args) {
        HotCode059 hotCode059 = new HotCode059();
        System.out.println(hotCode059.generateParenthesis(3));
    }

    private final List<String> result = new ArrayList<>();
    public List<String> generateParenthesis(int n) {
        bfs(n, n * 2, 0, 0, new StringBuffer());
        return result;
    }

    public void bfs(int n, int total, int prefixCount, int postCount, StringBuffer stringBuffer) {
        int count = prefixCount + postCount;
        if (count > total) {
            return ;
        }
        if (count == total) {
            result.add(new String(stringBuffer));
        }
        if (prefixCount < n) {
            stringBuffer.append('(');
            bfs(n, total, prefixCount + 1, postCount, stringBuffer);
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        }
        if (postCount < prefixCount) {
            stringBuffer.append(')');
            bfs(n, total,  prefixCount, postCount + 1, stringBuffer);;
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        }
    }
}
